package com.example.java_message_queue.mqserver;

import com.example.java_message_queue.common.*;
import com.example.java_message_queue.common.BasicProperties;
import com.example.java_message_queue.common.Consumer;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 表示整个服务器
// 和客户端通信
/*
 * 这里的技术选型:
 * 1. 自己写 socket , 自己定义二进制协议序列化.
 * 2. 自己写 socket, 使用Java标准库/第三方库序列化
 * 3. 使用 rpc 框架
 *
 * 第一种方案排除. 实现起来比较复杂.
 * 第二种方案可行性比较高. 实现成本较低. 前面已经用了序列化/反序列化操作了.
 * 只要在这个基础上再稍微封装下即可.
 * 第三种方案封装程度最高, 也最抽象. 代码最简单. 讲解成本更大. 同时有个问题, 就是后续出了 rpc 的教学内容, 和项目可能又对不上了. 比如这里用了 grpc, 后续出的是 dubbo, 就还麻烦.
 *
 * 综合下来是不是还是考虑使用方案二?
 * 方案三的话, 下个版本迭代的时候再扩展吧.
 * 现有的内容其实复杂程度已经不低了.
 *
 * Connection: 一个 TCP 的连接
 * Channel: 一个 TCP 连接内部的信道.
 * Connection 是一根网线; Channel 就是网线里面的线.
 *
 * 此处就写个简单的同步服务. 相当于在课堂代码的基础上, 加入了 "自定义协议" .
 */
public class BrokerServer {
    // 当前程序只考虑一个虚拟主机的情况.
    private VirtualHost virtualHost = new VirtualHost("default-VirtualHost");
    // key 为 channelId, value 为 channel 对应的 socket 对象.
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();

    private ServerSocket serverSocket;
    private ExecutorService executorService;
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("[BrokerServer] 启动完成!");
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                Socket clientSocket = serverSocket.accept();
                executorService.submit(() -> processConnection(clientSocket));
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器关闭完成!");
        }
    }

    public void stop() throws IOException {
        runnable = false;
        // 立即结束所有的线程池的任务
        executorService.shutdownNow();
        serverSocket.close();
    }

    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            while (true) {
                Request request = readRequest(dataInputStream);
                Response response = process(request, clientSocket);
                writeResponse(dataOutputStream, response);
            }
        } catch (EOFException | SocketException e) {
            System.out.println("[BrokerServer] connection 关闭! serverIP=" + clientSocket.getInetAddress().toString()
                    + ", port=" + clientSocket.getPort());
        } catch (MqException | IOException | ClassNotFoundException e) {
            System.out.println("[BrokerServer] connection 出现异常!");
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
                // 对 sessions 进行清理
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void clearClosedSession(Socket clientSocket) {
        // 这里不要一个循环, 同时遍历 + 删除. 否则可能有迭代器失效问题.
        List<String> toDeleteChannelId = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if (entry.getValue() == clientSocket) {
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for (String channelId : toDeleteChannelId) {
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理 session 完成! 被清理的 channelId=" + toDeleteChannelId);
    }

    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()) {
            throw new IOException("读取请求数据出错!");
        }
        request.setPayload(payload);
        return request;
    }

    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        dataOutputStream.flush();
    }

    // 下方的 processXXX 系列方法, 是非常相似的.
    // 但是 请求, 响应, 核心 api 都存在差异.
    private Response process(Request request, Socket clientSocket) throws MqException, IOException, ClassNotFoundException {
        // 1. 从 request 中解析出业务请求
        BaseArguments baseArguments = (BaseArguments) BinaryTool.fromBytes(request.getPayload());
        System.out.println("[Request] rid=" + baseArguments.getRid() + ", channelId=" + baseArguments.getChannelId()
                + ", type=" + request.getType() + ", length=" + request.getLength());
        // 2. 根据 type 来区分业务分支.
        boolean ok = true;
        if (request.getType() == 0x1) {
            // 创建 channel
            sessions.put(baseArguments.getChannelId(), clientSocket);
            System.out.println("[BrokerServer] 创建 channel 完成! channelId=" + baseArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            // 销毁 channel
            sessions.remove(baseArguments.getChannelId());
            System.out.println("[BrokerServer] 销毁 channel 完成! channelId=" + baseArguments.getChannelId());
        } else if (request.getType() == 0x3) {
            // 创建交换机
            ExchangeDeclareArguments exchangeDeclareArguments = (ExchangeDeclareArguments) baseArguments;
            ok = virtualHost.exchangeDeclare(exchangeDeclareArguments.getExchangeName(), exchangeDeclareArguments.getExchangeType(),
                    exchangeDeclareArguments.isDurable(), exchangeDeclareArguments.isAutoDelete(), exchangeDeclareArguments.getArguments());
        } else if (request.getType() == 0x4) {
            // 删除交换机
            ExchangeDeleteArguments exchangeDeleteArguments = (ExchangeDeleteArguments) baseArguments;
            ok = virtualHost.exchangeDelete(exchangeDeleteArguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            // 创建队列
            QueueDeclareArguments queueDeclareArguments = (QueueDeclareArguments) baseArguments;
            ok = virtualHost.queueDeclare(queueDeclareArguments.getQueueName(), queueDeclareArguments.isDurable(), queueDeclareArguments.isExclusive(),
                    queueDeclareArguments.isAutoDelete(), queueDeclareArguments.getArguments());
        } else if (request.getType() == 0x6) {
            // 删除队列
            QueueDeleteArguments queueDeleteArguments = (QueueDeleteArguments) baseArguments;
            ok = virtualHost.queueDelete(queueDeleteArguments.getQueueName());
        } else if (request.getType() == 0x7) {
            // 创建绑定
            QueueBindArguments queueBindArguments = (QueueBindArguments) baseArguments;
            ok = virtualHost.queueBind(queueBindArguments.getQueueName(), queueBindArguments.getExchangeName(), queueBindArguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            // 解除绑定
            QueueUnbindArguments queueUnbindArguments = (QueueUnbindArguments) baseArguments;
            ok = virtualHost.queueUnbind(queueUnbindArguments.getQueueName(), queueUnbindArguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            // 发送消息
            BasicPublishArguments basicPublishArguments = (BasicPublishArguments) baseArguments;
            ok = virtualHost.basicPublish(basicPublishArguments.getExchangeName(), basicPublishArguments.getRoutingKey(),
                    basicPublishArguments.getBasicProperties(), basicPublishArguments.getBody());
        } else if (request.getType() == 0xa) {
            // 订阅消息
            BasicConsumeArguments basicConsumeArguments = (BasicConsumeArguments) baseArguments;
            // 创建个回调, 用来把消费的数据转发回客户端.
            ok = virtualHost.basicConsume(basicConsumeArguments.getConsumeTag(), basicConsumeArguments.getQueueName(),
                    basicConsumeArguments.isAutoAck(), new Consumer() {
                        @Override
                        public void handleDelivery(String consumerTag, BasicProperties properties, byte[] body) throws MqException, IOException {
                            // 1. 根据 channelId 找到对应的 socket
                            Socket clientSocket = sessions.get(basicConsumeArguments.getChannelId());
                            if (clientSocket == null || clientSocket.isClosed()) {
                                throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭!");
                            }
                            // 2. 构造响应数据
                            SubScribeReturns subScribeReturns = new SubScribeReturns();
                            subScribeReturns.setChannelId(basicConsumeArguments.getChannelId());
                            subScribeReturns.setConsumerTag(consumerTag);
                            subScribeReturns.setBasicProperties(properties);
                            subScribeReturns.setBody(body);
                            byte[] payload = BinaryTool.toBytes(subScribeReturns);
                            // 3. 写入到对应 socket 中
                            Response response = new Response();
                            response.setType(0xc);
                            response.setLength(payload.length);
                            response.setPayload(payload);
                            // 此处不应该关闭 DataOutputStream, 关闭这个会导致内部持有的 clientSocket.getOutputStream 被关闭.
                            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            writeResponse(dataOutputStream, response);
                        }
                    });
        } else if (request.getType() == 0xb) {
            // 确认 ack
            BasicAckArguments basicAckArguments = (BasicAckArguments) baseArguments;
            ok = virtualHost.basicAck(basicAckArguments.getQueueName(), basicAckArguments.getMessageId());
        } else {
            throw new MqException("[BrokerServer] 未知的请求 type ! type=" + request.getType());
        }
        // 3. 构造响应.
        BaseReturns baseReturns = new BaseReturns();
        baseReturns.setRid(baseArguments.getRid());
        baseReturns.setChannelId(baseArguments.getChannelId());
        baseReturns.setOk(ok);

        byte[] payload = BinaryTool.toBytes(baseReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response] rid=" + baseReturns.getRid() + ", channelId=" + baseReturns.getChannelId()
                + ", type=" + response.getType() + ", length=" + response.getLength());
        return response;
    }
}
